package com.yida.gwj.expend.handler;

import java.util.Optional;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.yida.common.core.constant.SecurityConstants;
import com.yida.common.core.domain.R;
import com.yida.common.core.exception.ServiceException;
import com.yida.gwj.api.domain.GwjConfBusinessFlag;
import com.yida.gwj.api.domain.GwjConfStep;
import com.yida.gwj.api.service.RemoteGwjConfigService;
import com.yida.gwj.common.enums.GwjBusinessFlagType;
import com.yida.gwj.common.enums.GwjBusinessLogResult;
import com.yida.gwj.common.utils.GwjEnumUtils;
import com.yida.gwj.expend.domain.GwjMaintenanceFundsBusiness;
import com.yida.gwj.expend.domain.GwjMaintenanceFundsBusinessLog;
import com.yida.gwj.expend.domain.message.MqBaseResult;
import com.yida.gwj.expend.domain.message.PreAcceptSubmitMessage;
import com.yida.gwj.expend.domain.request.GwjMaintenanceFundsBusinessRequest;
import com.yida.gwj.expend.enums.BusinessModuleTypeEnum;
import com.yida.gwj.expend.enums.BusinessServerStatusEnum;
import com.yida.gwj.expend.enums.BusinessStatusEnum;
import com.yida.gwj.expend.enums.FlagStatusEnum;
import com.yida.gwj.expend.enums.MaintenanceFundsErrorEnum;
import com.yida.gwj.expend.service.IGwjMaintenanceFundsBusinessLogService;
import com.yida.gwj.expend.service.IGwjMaintenanceFundsBusinessService;

import cn.hutool.core.date.DateTime;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.json.JSONUtil;

/**
 * 维修基金前服务抽象
 *
 * @author liangp
 * @date 2023/04/10
 */
@Component
public abstract class AbstractExpendPreService {

    private final static Logger log = LoggerFactory.getLogger(AbstractExpendPreService.class);

    @Autowired
    private RemoteGwjConfigService remoteGwjConfigService;
    @Autowired
    private IGwjMaintenanceFundsBusinessService maintenanceFundsBusinessService;
    @Autowired
    private IGwjMaintenanceFundsBusinessLogService maintenanceFundsBusinessLogService;

    public AbstractExpendPreService() {}

    public AbstractExpendPreService(RemoteGwjConfigService remoteGwjConfigService, IGwjMaintenanceFundsBusinessService maintenanceFundsBusinessService, IGwjMaintenanceFundsBusinessLogService maintenanceFundsBusinessLogService) {
        this.remoteGwjConfigService = remoteGwjConfigService;
        this.maintenanceFundsBusinessService = maintenanceFundsBusinessService;
        this.maintenanceFundsBusinessLogService = maintenanceFundsBusinessLogService;
    }

    /**
     * 一次补件提交
     *
     * @param mqBaseResult
     */
    void preAcceptSubmit(MqBaseResult mqBaseResult, GwjBusinessFlagType businessFlagType) {
        PreAcceptSubmitMessage preAcceptSubmitMessage = JSONUtil.toBean(mqBaseResult.getJsonMsg(), PreAcceptSubmitMessage.class);
        if (ObjectUtil.isNull(preAcceptSubmitMessage)) {
            log.error("PreAcceptSubmitMessage数据转换异常");
            return;
        }
        try {
            preAcceptSubmitMessage.checkNull();
        } catch (Exception e) {
            log.error("PreAcceptSubmitMessage数据校验异常");
            return;
        }
        BusinessModuleTypeEnum[] deleteModuleTypeEnums = null;
        GwjMaintenanceFundsBusiness oldMaintenanceFundsBusiness = preAcceptSubmitMessage.getMaintenanceFundsBusiness();
        GwjMaintenanceFundsBusiness maintenanceFundsBusiness = maintenanceFundsBusinessService.getGwjMaintenanceFundsBusiness(new GwjMaintenanceFundsBusinessRequest() {
            {
                setOutServerIdentification(oldMaintenanceFundsBusiness.getServerIdentification());
            }
        });
        Long businessId = null;
        if (ObjectUtil.isNull(maintenanceFundsBusiness)) {
            try {
                R<GwjConfBusinessFlag> r = remoteGwjConfigService.selectGwjConfBusinessFlagByBizFlagId(businessFlagType.getCode(), SecurityConstants.INNER);
                if (R.isError(r)) {
                    throw new ServiceException(r.getMsg());
                }
                if (ObjectUtil.isNull(r.getData())) {
                    throw new ServiceException(r.getMsg());
                }
                oldMaintenanceFundsBusiness.setFlowId(r.getData().getFlowId());
            } catch (Exception e) {
                log.error("远程调用 -> [remoteGwjConfigService][selectGwjConfBusinessFlagByBizFlagId]异常,异常信息: [{}]", e);
                throw new ServiceException("远程调用 -> [remoteGwjConfigService][selectGwjConfBusinessFlagByBizFlagId]异常");
            }
            try {
                R<GwjConfStep> r = remoteGwjConfigService.getFirstStep(businessFlagType.getCode(), SecurityConstants.INNER);
                if (R.isError(r)) {
                    throw new ServiceException(r.getMsg());
                }
                if (ObjectUtil.isNull(r.getData())) {
                    throw new ServiceException(r.getMsg());
                }
                oldMaintenanceFundsBusiness.setStepId(r.getData().getStepId());
            } catch (Exception e) {
                log.error("远程调用 -> [remoteGwjConfigService][selectGwjConfStepListByFlagId]异常,异常信息: [{}]", e);
                throw new ServiceException("远程调用 -> [remoteGwjConfigService][selectGwjConfStepListByFlagId]异常");
            }
            oldMaintenanceFundsBusiness.setBizId(null);
            oldMaintenanceFundsBusiness.setCreateTime(DateTime.now());
            oldMaintenanceFundsBusiness.setUpdateTime(DateTime.now());
            oldMaintenanceFundsBusiness.setCreateBy(preAcceptSubmitMessage.getMaintenanceFundsBusiness().getCreateBy());
            oldMaintenanceFundsBusiness.setUpdateBy(preAcceptSubmitMessage.getMaintenanceFundsBusiness().getUpdateBy());
            oldMaintenanceFundsBusiness.setStatus(BusinessStatusEnum.SUBMIT.getCode());
            oldMaintenanceFundsBusiness.setOutServerIdentification(oldMaintenanceFundsBusiness.getServerIdentification());
            oldMaintenanceFundsBusiness.setBizFlagId(businessFlagType.getCode());
            oldMaintenanceFundsBusiness.setServerIdentification(IdUtil.getSnowflakeNextIdStr());
            // 20230725
            oldMaintenanceFundsBusiness.setCurrentOperId(null);
            oldMaintenanceFundsBusiness.setCurrentOperName("系统管理员");
        } else {
            businessId = maintenanceFundsBusiness.getBizId();
            if (ObjectUtil.notEqual(maintenanceFundsBusiness.getStatus(), BusinessStatusEnum.RETREAT_PARTS.getCode())) {
                throw new ServiceException("GwjMaintenanceFundsBusiness状态不对");
            }
            preAcceptSubmitMessage.setMaintenanceFundsBusiness(new GwjMaintenanceFundsBusiness() {
                {
                    setBizId(maintenanceFundsBusiness.getBizId());
                    setStatus(BusinessStatusEnum.TAKE_PARTS.getCode());
                    setServerStatus(BusinessServerStatusEnum.NORMAL.getCode());
                    setServerIdentification(maintenanceFundsBusiness.getServerIdentification());
                    // 20230725新增修改字段 后期考虑优化 先这么玩
                    // 联系人
                    setContacts(oldMaintenanceFundsBusiness.getContacts());
                    // 联系电话
                    setPhone(oldMaintenanceFundsBusiness.getPhone());
                    // 小区地址
                    setAddress(oldMaintenanceFundsBusiness.getAddress());
                    // 业务名称
                    setBizName(oldMaintenanceFundsBusiness.getBizName());
                    // 项目竣工时间
                    setCompletedTime(oldMaintenanceFundsBusiness.getCompletedTime());
                    // 保修有效期
                    setValidDate(oldMaintenanceFundsBusiness.getValidDate());

                }
            });
            deleteModuleTypeEnums = new BusinessModuleTypeEnum[] {BusinessModuleTypeEnum.INFO, BusinessModuleTypeEnum.COMMUNITY, BusinessModuleTypeEnum.BUILD, BusinessModuleTypeEnum.HOUSE, BusinessModuleTypeEnum.OWNER, BusinessModuleTypeEnum.ATTACHMENT};
        }
        // 20230613 hmh 一次补件，默认当前办事员为系统管理员，id=null,后期取件后，做相应变更 start
        // 20230710 hmh 修订，提交时候只有原状态不是退件的才修改管理员信息。
        // Integer code = BusinessStatusEnum.RETREAT_PARTS.getCode();
        // if (StringUtils.isNotNull(maintenanceFundsBusiness) && !code.equals(maintenanceFundsBusiness.getStatus()) &&
        // !code.equals(maintenanceFundsBusiness.getServerStatus())) {
        // preAcceptSubmitMessage.getMaintenanceFundsBusiness().setCurrentOperId(null);
        // preAcceptSubmitMessage.getMaintenanceFundsBusiness().setCurrentOperName("系统管理员");
        // }
        // end
        Optional<GwjMaintenanceFundsBusiness> maintenanceFundsBusiness1 = Optional.ofNullable(maintenanceFundsBusinessService.delete4Save(bizId -> Optional.of(preAcceptSubmitMessage), businessId, deleteModuleTypeEnums).<ServiceException>orElseThrow(() -> {
            throw new ServiceException("delete4Save异常");
        }));
        int insertFlag = maintenanceFundsBusinessLogService.insertGwjMaintenanceFundsBusinessLog(new GwjMaintenanceFundsBusinessLog() {
            {
                setResult(GwjBusinessLogResult.SUBMIT.getCode());
                setBizId(maintenanceFundsBusiness1.get().getBizId());
                setStepId(maintenanceFundsBusiness1.get().getStepId());
                setOperId(maintenanceFundsBusiness1.get().getApplicantUserId());
                setOperName(maintenanceFundsBusiness1.get().getApplicantUserName());
            }
        });
        if (ObjectUtil.equal(FlagStatusEnum.FAL.getCode(), insertFlag)) {
            throw new ServiceException(GwjEnumUtils.getEnumConstantMsg(MaintenanceFundsErrorEnum.MQ_PRE_ACCEPT_SUBMIT) + "签署意见新增失败");
        }
    }

}
